package com.ruoyi.web.controller.recipe;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recipe.domain.RecipeDish;
import com.ruoyi.recipe.domain.RecipeDishItem;
import com.ruoyi.recipe.service.IRecipeDishService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.recipe.domain.RecipeDishStep;
import com.ruoyi.recipe.service.IRecipeDishStepService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 步骤Controller
 * 
 * @author ruoyi
 * @date 2024-11-23
 */
@Controller
@RequestMapping("/recipe/step")
public class RecipeDishStepController extends BaseController
{
    private String prefix = "recipe/step";

    @Autowired
    private IRecipeDishStepService recipeDishStepService;

    @Autowired
    private IRecipeDishService recipeDishService;

    @RequiresPermissions("recipe:step:view")
    @GetMapping()
    public String step()
    {
        return prefix + "/step";
    }

    /**
     * 查询步骤列表
     */
    @RequiresPermissions("recipe:step:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(RecipeDishStep recipeDishStep)
    {
        startPage();
        List<RecipeDishStep> list = recipeDishStepService.selectRecipeDishStepList(recipeDishStep);
        return getDataTable(list);
    }

    /**
     * 导出步骤列表
     */
    @RequiresPermissions("recipe:step:export")
    @Log(title = "步骤", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(RecipeDishStep recipeDishStep)
    {
        List<RecipeDishStep> list = recipeDishStepService.selectRecipeDishStepList(recipeDishStep);
        ExcelUtil<RecipeDishStep> util = new ExcelUtil<RecipeDishStep>(RecipeDishStep.class);
        return util.exportExcel(list, "步骤数据");
    }

    /**
     * 新增步骤
     */
    @GetMapping("/add/{dishId}")
    public String add(@PathVariable("dishId") Long dishId, ModelMap mmap)
    {
        RecipeDish recipeDish = recipeDishService.selectRecipeDishByDishId(dishId);
        mmap.put("recipeDish", recipeDish);
        return prefix + "/add";
    }

    /**
     * 新增保存步骤
     */
    @RequiresPermissions("recipe:step:add")
    @Log(title = "步骤", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(RecipeDishStep recipeDishStep)
    {
        return toAjax(recipeDishStepService.insertRecipeDishStep(recipeDishStep));
    }

    /**
     * 修改步骤
     */
    @RequiresPermissions("recipe:step:edit")
    @GetMapping("/edit/{stepId}")
    public String edit(@PathVariable("stepId") Long stepId, ModelMap mmap)
    {
        RecipeDishStep recipeDishStep = recipeDishStepService.selectRecipeDishStepByStepId(stepId);
        mmap.put("recipeDishStep", recipeDishStep);
        return prefix + "/edit";
    }

    /**
     * 修改保存步骤
     */
    @RequiresPermissions("recipe:step:edit")
    @Log(title = "步骤", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(RecipeDishStep recipeDishStep)
    {
        return toAjax(recipeDishStepService.updateRecipeDishStep(recipeDishStep));
    }

    /**
     * 删除步骤
     */
    @RequiresPermissions("recipe:step:remove")
    @Log(title = "步骤", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(recipeDishStepService.deleteRecipeDishStepByStepIds(ids));
    }

    /**
     * 导入模板下载
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<RecipeDishStep> util = new ExcelUtil<RecipeDishStep>(RecipeDishStep.class);
        return util.importTemplateExcel("菜品步骤导入模板");
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) {
        try {
            ExcelUtil<RecipeDishStep> util = new ExcelUtil<RecipeDishStep>(RecipeDishStep.class);
            List<RecipeDishStep> list = util.importExcel(file.getInputStream());
            String message = importDishStep(list, updateSupport);
            return AjaxResult.success(message);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    public String importDishStep(List<RecipeDishStep> list, Boolean isUpdateSupport) throws Exception {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new Exception("导入菜品步骤数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<RecipeDish> dishList = recipeDishService.selectRecipeDishList(null);
        // categoryName categoryId键值对
        Map<String, Long> dishMap = new HashMap<>();
        for (RecipeDish dish : dishList) {
            dishMap.put(dish.getDishName(), dish.getDishId());
        }

        Iterator<RecipeDishStep> iterator = list.iterator();
        while (iterator.hasNext()) {
            RecipeDishStep item = iterator.next();

            if (failureNum >= 10) {
                break;
            }

            if (StringUtils.isEmpty(item.getDishName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、菜品名称不能为空");
                iterator.remove();
                continue;
            }
            if (StringUtils.isEmpty(item.getStepDesc())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、步骤描述不能为空");
                iterator.remove();
                continue;
            }
            if (StringUtils.isEmpty(item.getStepPic())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、步骤图片不能为空");
                iterator.remove();
                continue;
            }
            if (StringUtils.isNull(dishMap.get(item.getDishName()))) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、" + item.getDishName() + " - 步骤" + item.getStepSort() + " 导入失败：未找到该菜品");
                iterator.remove();
                continue;
            }

            item.setDishId(dishMap.get(item.getDishName()));
            item.setCreateBy("");
            item.setStatus("0");
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！请修改文件后重试：");
            throw new Exception(failureMsg.toString());
        }

        int rows = recipeDishStepService.batchInsertRecipeDishStep(list);

        if (rows <= 0) {
            failureMsg.insert(0, "很抱歉，导入失败：保存数据失败");
            throw new Exception(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + rows + " 条");
        }
        return successMsg.toString();
    }
}
